<template>
    <div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box;overflow:hidden;">
        <div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px;">
            <div v-if="$hasPer('MyExam:excel')" class="search-s page-public-s" style="box-sizing: border-box;">
                <el-card shadow="never" :body-style="{ paddingBottom: '0' }">
                    <el-form class="box-f" ref="queryForm" :inline="true">
                        <el-form-item>
                            <el-button @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>
            
            <div style="box-sizing: border-box;" class="flex-1 pos-r">
                <div class="pos-a w-h-100" style="box-sizing: border-box;">
                    <el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px;">
                        <div style="" class="w-h-100 ver-flex">
                            <div class="flex-1 pos-r">
                                <div class="pos-a w-h-100">
                                    <el-table ref="excelRef" :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
                                        <!-- <el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" /> -->

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="课程名称"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="s_Plan" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.v_CourseName">{{ scope.row.v_CourseName }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" prop="v_SysUserName" label="用户名称"  align="center" />

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="试卷总分"  align="center" prop="n_FullScore" sortable>
                                            <template #default="scope">
                                                <span v-if="scope.row.n_FullScore">{{ scope.row.n_FullScore }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" prop="n_Score" label="考试得分" sortable align="center">
                                            <template #default="scope">
                                                <span v-if="scope.row.n_Score">{{ scope.row.n_Score }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="分数等级"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="s_Scope" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.v_ScopeStageName">{{ scope.row.v_ScopeStageName }}</span>
                                                    <span v-else>-</span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" prop="d_StartTime" label="考试开始时间"  align="center" sortable />

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="考试结束时间"  align="center" prop="d_EndTime" sortable>
                                            <template #default="scope">
                                                <span v-if="scope.row.d_EndTime">{{ scope.row.d_EndTime }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true"  label="考试用时" align="center" prop="n_UsedTime" sortable>
                                            <template #default="scope">
                                                <span v-if="scope.row.n_UsedTime">{{ scope.row.n_UsedTime }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="试卷状态"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="s_State" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.n_State === 0" style="color:#E6A23C;">{{scope.row.v_StateName}}</span>
                                                    <span v-else-if="scope.row.n_State === 1" style="color:#67C23A;">{{scope.row.v_StateName}}</span>
                                                    <span v-else-if="scope.row.n_State === 2" style="color:#F56C6C;">{{scope.row.v_StateName}}</span>
                                                    <span v-else>-</span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="180" :show-overflow-tooltip="true" prop="createdTime" label="创建时间"  align="center" sortable>
                                            <template #default="scope">
                                                <span v-if="scope.row.createdTime">{{ scope.row.createdTime }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="180" :show-overflow-tooltip="true" prop="updatedTime" label="更新时间"  align="center" sortable>
                                            <template #default="scope">
                                                <span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>
                                        
                                        <el-table-column width="260" label="操作" align="center" fixed="right">
                                            <el-table-column :show-overflow-tooltip="true" width="260" align="center">
                                                <template #header>
                                                    <el-button class="icon-e" @click='searchClick' icon="ele-Search" size="small" type="primary" text> 查询 </el-button>
                                                    <el-button class="icon-e clear-bg" style="background-color: transparent !important;" size="small" @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
                                                </template>
                                                <template #default="scope">
                                                    <div class="operate-s">
                                                        <el-button @click="detailHandle(scope.row.id)" class="icon-e" icon="ele-View" size="small" text type="success">详情</el-button>
                                                        <el-button v-if="$hasPer('MyExam:viewPaper')" @click="userPaperHandle(scope.row)" class="icon-e" icon="ele-View" size="small" text type="primary">查看用户考卷</el-button>
                                                        <el-button v-if="$hasPer('MyExam:alignExam')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="warning">重新考试</el-button>
                                                        <!-- <el-button v-if="scope.row.n_State !== 0" @click="userPaperHandle(scope.row)" class="icon-e" icon="ele-View" size="small" text type="primary">查看用户考卷</el-button>
                                                        <el-button v-if="scope.row.n_State !== 0" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="warning">重新考试</el-button>
                                                        <el-button v-else disabled class="icon-e" icon="ele-Discount" size="small" text type="primary">考试进行中</el-button> -->
                                                    </div>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </div>
                            <div style="height: 30px;margin-top: 20px;" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
                        </div>
                    </el-card>
                </div>
            </div>
        </div>
        <AddEditExaminationPaper
            :repairInfo="repairInfo"
            :isUseDialog="isUseDialog"
            @cancelUseClick="cancelUseClick"
            @controlUseClick="controlUseClick"
        />
        <!-- 在线考试 -->
        <OnlineExam
            :repairInfo="examInfo"
            :isUseDialog="examDialog"
            @cancelExamClick="cancelExamClick"
            @controlExamClick="controlExamClick"
            @updateData="getData"
        />
        <!-- 查看用户考卷 -->
        <DoExercise
            setStatus="detail"
            :repairInfo="paperInfo"
            :isUseDialog="paperDialog"
            @cancelPaperClick="cancelPaperClick"
        />
        <!-- 详情 -->
        <DetailModel
            :detailInfo="detailInfo"
            :MdetailDialog="MdetailDialog"
            labelWidth="140px"
            @cancelDetailClick="cancelDetailClick"
        />
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref, onMounted , reactive , toRaw } from 'vue';
import getTableData from '/@/utils/getTableData';
import { 
    OmsEduExamOLPage , 
    OmsEduExamOLStartTheExamination , 
    EduTrainingPlanList , 
    OmsEduExamOLDetail ,
    UserExamPaperList ,
    sysUserdetail,
} from '/@/api/centerControl/sms';
import AddEditExaminationPaper from '../component/sms/add-edit-ExaminationPaper.vue';
import OnlineExam from '../component/sms/online-exam.vue';
import { onBeforeRouteLeave } from 'vue-router';
import { getUserInfo } from '/@/api/user';
import SearchModel from '../component/search-model.vue';
import DetailModel from '../component/detail-model.vue';
import DoExercise from '../component/sms/do-exercise.vue';
import { ElMessage } from 'element-plus';
import { exportToExcel } from '/@/utils/exportToExcel';

export default defineComponent( {
    name: 'MyExam',
    components: {
        AddEditExaminationPaper,
        OnlineExam,
        SearchModel,
        DetailModel,
        DoExercise,
    },
    setup(props){
        const isUseDialog = ref(); // 新增/编辑弹出框隐藏/显示
        const repairInfo = ref(); // 传递子组件数据
        const l_TrainingPlanId = localStorage.getItem('l_TrainingPlanId');
        let userInfo:any = '';
        const examInfo = ref();
        const examDialog = ref(false);

        const paperInfo = ref();
        const paperDialog = ref(false);

        /*** 功能点击事件 */
        const nodeClick = (val:any) => {
            let getPaper = getPaperFun(val.l_TrainingPlanId,userInfo.id);
            getPaper.then((res: any) => {
                let setObj: any = {};
                let totalNum = 0;
                res.map((i: any) => {
                    totalNum += i.n_Score;
                });
                setObj.titleCon = val.v_CourseName;
                setObj.paperName = val.v_Name;
                setObj.paperArr = res;
                setObj.totalNum = totalNum;
                setObj.userId = userInfo.id;
                setObj.l_TrainingPlanId = val.l_TrainingPlanId;
                setObj.setStatus = 'anew';
                examInfo.value = JSON.stringify(setObj);
                examDialog.value = true;
            });
        };

        /*** getPaperFun 在线考试试卷获取 */
        const getPaperFun = async(val: number, userId: number) => {
            let param: any = {}
            param.l_TrainingPlanId = val;
            param.l_SysUserId = userId;
            let res: any = await OmsEduExamOLStartTheExamination(param);
            console.log(res,'题库数据')
            if(res.success) return res.data;
        };

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            isUseDialog.value = false
        };

        /*** controlUseClick 提交事件 */
        const controlUseClick = () => {
            isUseDialog.value = false
        };

        onBeforeRouteLeave((to, from, next) => {
            if(l_TrainingPlanId) localStorage.removeItem('l_TrainingPlanId');
            next()
        });

        /** controlExamClick 重新考试提交事件 */
        const controlExamClick = () => {
            examDialog.value = false;
        }

        /*** cancelExamClick 在线考试取消事件 */
        const cancelExamClick = () => {
            examDialog.value = false;
        };

        /*** 查看用户考卷 */
        const userPaperHandle = async (val: any) => {
            if(val.n_State === 0){
                ElMessage({
                    type: 'error',
                    message: '考试进行中...',
                })
            }else{
                let param: any = {};
                param.l_TrainingPlanId = val.l_TrainingPlanId;
                param.l_SysUserId = userInfo.id;
                let res: any = await UserExamPaperList(param);
                let ras: any = await sysUserdetail({ id: val.l_SysUserId});
                let setObj: any = {};
                let totalNum = 0;
                res.data.map((i: any) => {
                    totalNum += i.n_Score;
                    i.options = i.examPaperDe;
                });
                if(Object.keys(ras.data).length !== 0 && ras.success){
                    if(ras.data.sysEmpInfo && Object.keys(ras.data.sysEmpInfo).length !== 0){
                        setObj.orgName = ras.data.sysEmpInfo.orgName;
                        setObj.empName = ras.data.sysEmpInfo.empName;
                    }
                }
                setObj.titleCon = val.v_CourseName;
                setObj.paperArr = res.data;
                setObj.totalNum = totalNum;
                paperInfo.value = JSON.stringify(setObj);
                paperDialog.value = true;
            }
        }
        
        /*** cancelPaperClick 在线刷题关闭事件 */
        const cancelPaperClick = () => {
            paperDialog.value = false;
        }

        /*** ================================= 详情类数据操作 =================================  */
        const MdetailDialog = ref(false);
        const detailInfo = ref();
        /*** 获取详情接口数据 */
        const getDetailFun = async (id: number) => {
            let res: any = await OmsEduExamOLDetail({id: id});
            if(res.success){
                let setArr: any = [];
                let tableArr: any = [];
                let detailObj: any = {};
                detailObj['课程名称'] = res.data.v_CourseName;
                detailObj['用户名称'] = res.data.v_SysUserName;
                detailObj['试卷总分'] = res.data.n_FullScore;
                detailObj['考试得分'] = res.data.n_Score;
                detailObj['分数等级名称'] = res.data.v_ScopeStageName;
                detailObj['考试开始时间'] = res.data.d_StartTime;
                detailObj['考试结束时间'] = res.data.d_EndTime;
                detailObj['考试用时(分钟)'] = res.data.n_UsedTime;
                detailObj['在线考试试卷状态'] = res.data.v_StateName;
                setArr = [{
                    formTitle: '基础信息',
                    type: 'form',
                    info: detailObj,
                }];
                detailInfo.value = setArr;
                MdetailDialog.value = true;
            }
        }
        /*** 详情 */
        const detailHandle = (id: number) => {
            getDetailFun(id);
        }
        /*** 详情关闭事件 */
        const cancelDetailClick = () => {
            MdetailDialog.value = false;
        }
        /*** ================================= 详情类数据操作 =================================  */
        
        /*** ================================= 查询类数据操作 =================================  */
        let searchObj:any = reactive({
            l_SysUserId: 0
        });
        const basicsInfo: any = ref([]);
        const searInfo: any = ref();

        /*** 获取需要查询的数据 */
        const searchHandel = (val: any) => {
            searInfo.value = val;
        }

        /*** 查询按钮 */
        const searchClick = () => {
            let newObj = Object.keys(searInfo.value);
            if(newObj.length !== 0){
                newObj.map((i:any) => {
                    searchObj[i] = searInfo.value[i];
                })
            }
        };

        /*** 重置按钮 */
        const resetClick = () => {
            searInfo.value = {};
            let newObj = Object.keys(searchObj);
            if(newObj.length !== 0){
                newObj.map((i:any) => {
                    searchObj[i] = ''
                })
            }
            searchObj.l_SysUserId = useDefaultVal;
            initInfoFun();
        };
        
        let planArr: any = [];
        let useDefaultVal: number = 0;

        /*** 获取用户信息 */
        const getUserFun = async() => {
            let res:any = await getUserInfo();
            if(res.success){
                userInfo = res.data;
                searchObj.l_SysUserId = res.data.id;
                useDefaultVal = res.data.id;
            }
        }

        /*** getPlanList 获取培训计划列表 */
        const getPlanList = async() => {
            let param = {}
            let res:any = await EduTrainingPlanList(param);
            if(res.success && res.data.length !==0){
                res.data.map((item: any) => {
                    item.label = item.v_CourseName;
                    item.value = item.id;
                });
                planArr = res.data;
            }
        };
        
        /*** 初始化数据 */
        const initInfoFun = () => {
            basicsInfo.value = [{
                    typeId: 's_Plan', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'l_TrainingPlanId', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '培训计划', // placeholder数据
                    defaultProp: planArr, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'change', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'planChange', // 事件名称 --- 选填
                },{
                    typeId: 's_Scope', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'n_ScopeStage', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '分数等级', // placeholder数据
                    defaultProp: [
                        {label: '优秀', value: 0},
                        {label: '合格', value: 1},
                        {label: '不合格', value: 2},
                    ], // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'change', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'scopeChange', // 事件名称 --- 选填
                },{
                    typeId: 's_State', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'n_State', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '试卷状态', // placeholder数据
                    defaultProp: [
                        {label: '进行中', value: 0},
                        {label: '已完成', value: 1},
                        {label: '作废', value: 2},
                    ], // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'change', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'scopeChange', // 事件名称 --- 选填
                }
            ]
        }
        
        onMounted(async() => {
            await getUserFun();
            await getPlanList();
            initInfoFun();
        });
        /*** ================================= 查询类数据操作 =================================  */

        /*** ================================= 导出数据函数操作 ================================= */
        const excelRef: any = ref(null);
        const handleExport = () => {
            if(excelRef.value){
                if(excelRef.value.data.length !== 0){
                    let tableExcel: any = [];
                    let tableArr = excelRef.value.data;
                    tableArr.map((item: any) => {
                        let tableObj: any = {};
                        tableObj['课程名称'] = item.v_CourseName ? item.v_CourseName : '-';
                        tableObj['用户名称'] = item.v_SysUserName ? item.v_SysUserName : '-';
                        tableObj['试卷总分'] = item.n_FullScore ? item.n_FullScore : '-';
                        tableObj['考试得分'] = item.n_Score ? item.n_Score : '-';
                        tableObj['分数等级名称'] = item.v_ScopeStageName ? item.v_ScopeStageName : '-';
                        tableObj['考试开始时间'] = item.d_StartTime ? item.d_StartTime : '-';
                        tableObj['考试结束时间'] = item.d_EndTime ? item.d_EndTime : '-';
                        tableObj['考试用时(分钟)'] = item.n_UsedTime ? item.n_UsedTime : '-';
                        tableObj['在线考试试卷状态'] = item.v_StateName ? item.v_StateName : '-';
                        tableExcel.push(tableObj);
                    });
                    exportToExcel(tableExcel,'我的考试.xlsx');
                }else{
                    ElMessage({
                        type: 'error',
                        message: '暂无数据导出',
                    })
                }
            }
        }
        /*** ================================= 导出数据函数操作 ================================= */

        return {
            ...getTableData(OmsEduExamOLPage,{},searchObj),
            isUseDialog,
            cancelUseClick,
            controlUseClick,
            nodeClick,
            repairInfo,
            examDialog,
            examInfo,
            cancelExamClick,
            controlExamClick,
            userPaperHandle,
            paperInfo,
            paperDialog,
            cancelPaperClick,

            // 导出Excel
            excelRef,
            handleExport,
            
            // 详情
            MdetailDialog,
            detailHandle,
            detailInfo,
            cancelDetailClick,

            // 查询事件
            basicsInfo,
            searchHandel,
            searchClick,
            resetClick,
        }
    },
} )
</script>
<style lang="scss"> @import '../style/public.scss'; </style>
<style scoped lang="scss">
    #friend-merchant-manage {
        .box-f{
            :deep(.el-form-item__label){
                padding: 0;
            }
        }
        :deep(.el-card__body) {
            height: 100%;
        }
        :deep(.el-card){
            border: none !important;
        }
        .upload-demo{
            margin-left: 12px;
            margin-top: 2px;
        }
        ul {

            list-style: none;

            li {
                cursor: pointer;

                &:hover {
                    color: red;
                }
            }
        }
        .icon-e{
            :deep(.el-icon){
                margin-right: 0px!important;
            }
        }
    }
.clear-bg{
    background-color: transparent !important;
}
</style>